<template>
  <div class="fire-info">
    <el-row :gutter="10" class="in-box">
      <el-col :span="10" class="in-box-box">
        <div class="info">
          <p>
            <span>试验名称：</span>
            <span>{{ props.getInfo?.name }}</span>
          </p>
          <p>
            <span>炉型：</span>
            <span>{{ dataList.furnaceSize[Number(props.getInfo?.burner)] }}</span>
          </p>
        </div>
        <div class="table" ref="tableRef">
          <el-table
            :data="videoList"
            row-key="index"
            @selection-change="handleSelectionChange"
            @row-click="rowClick"
          >
            <el-table-column type="selection" width="30" />
            <el-table-column type="index" label="序号" width="50" align="center" />
            <el-table-column prop="filename" width="auto" label="视频名称" align="center">
              <template #default="scope">
                <span style="cursor: pointer">{{ scope.row.filename }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="burner_position" width="100" label="燃烧器位置" align="center" />
            <el-table-column prop="created_time" label="录制时间" align="center" width="auto">
              <template #default="scope">
                <span>
                  {{
                  scope.row.created_time
                  ? getDateStr(
                  scope.row.created_time.toString().split(".")[0] * 1000
                  )
                  : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column width="60" label="操作" align="center">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click.stop="deleteVideo(scope.row.filename)"
                  size="small"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="10">
        <div class="center-info">
          <el-checkbox v-model="radiusChecked" :disabled="!ifShowCircle" label="切圆显示" />
          <el-button class="margin" @click="updateCamera()">镜头矫正</el-button>
          <el-button class="margin" @click="pictureRotation()">画面旋转</el-button>
        </div>
        <!-- @changeImgFlag="changeImgFlagFn" -->
        <div class="center-con" id="centerBox2">
          <cutCirle :imgFlag="imgFlag" :isShowChecked="radiusChecked" :cx="cx" :cy="cy" :rx="rx" :ry="ry" :scaling_ratio="scaling_ratio"></cutCirle>
          <div class="center-bottom">
            <el-button
              class="margin"
              :icon="iconIdentify"
              type="primary"
              @click="clickCircularPatternRecognition()"
              v-if="!ifShowCircleButton"
              :loading="dialogQYSBVisible"
            >切圆识别</el-button>
            <el-button
              class="margin"
              :icon="iconIdentify"
              type="primary"
              v-if="ifShowCircleButton"
              @click="isClickCircularPatternRecognition()"
            >停止识别</el-button>
            <el-button
              class="margin"
              :icon="iconExport"
              type="primary"
              @click="clickExportRecording()"
            >视频导出</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="4" class="right_btn_container">
        <div class="top">
          <el-button class="margin" @click="reset()">返回</el-button>
        </div>
        <div class="center"></div>
        <div class="buttom">
          <div class="right_btn_bottom">
            <span class="span_title" style="color: #0f1a58; font-weight: 700">切圆信息</span>
            <div>
              <span class="span_title">位置</span>
              <span style="color: #0f1a58; font-weight: 700">
                圆心（{{ showCircularInfo.center_x }}mm,
                {{ showCircularInfo.center_y }}mm）
              </span>
            </div>

            <div>
              <span class="span_title">大小</span>
              <span
                style="color: #0f1a58; font-weight: 700"
              >前后直径 {{ showCircularInfo.front_back_diameter }}mm</span>
              <br />
              <span
                style="
                  color: #0f1a58;
                  font-weight: 700;
                  margin-left: calc(2em + 10px);
                "
              >侧向直径 {{ showCircularInfo.side_diameter }}mm</span>
            </div>
            <div>
              <el-button class="my_btn" @click="exportCorners">导出</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  <el-dialog
    v-model="dialogCameraVisible"
    title="镜头矫正"
    :width="jingtouW + 50 + 'px'"
    :before-close="handleCameraClose"
  >
    <camera ref="cameraRef" :dialogCameraVisible="dialogCameraVisible" :jingtouW="jingtouW" :jingtouH="jingtouH"></camera>
    <template #footer>
      <div class="dialog-footer">
        <el-button style="color: #0f1a58" @click="closeJz();">取消</el-button>
        <el-button type="primary" @click="submitCamera">确定</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="dialogRotationVisible"
    title="画面旋转"
    width="700"
    :before-close="handleRotationClose"
  >
    <rotation></rotation>
    <template #footer>
      <div class="dialog-footer">
        <el-button style="color: #0f1a58" @click="dialogRotationVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogRotationVisible = false">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="dialogVideoVisible"
    title="切圆测试结果"
    width="1000"
    :before-close="handleVideoClose"
  >
    <exportCorner @closeDialog="onChangeDialog" :dialogVideoVisible="dialogVideoVisible" :bfVideoName="bfVideoName" :bfVideoId="bfVideoId"></exportCorner>
  </el-dialog>
</template>
<script setup>
import * as echarts from "echarts";
import {
  toRefs,
  onMounted,
  ref,
  defineProps,
  nextTick,
  defineEmits
} from "vue";
import cutCirle from "./cutcircle.vue";
import dataListStore from "../stores/dataList";
import {
  listRecordings,
  deleteRecording,
  correctionCorners,
  startVideo,
  stopVideo,
  setVideoCorrection,
  resetToZero
} from "../http/video";
import { getDateStr } from "../utils/index.js";
import camera from "./camera.vue";
import rotation from "./rotation.vue";
import iconExport from "./iconExport.vue";
import iconIdentify from "../components/iconIdentify.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import iconError from "../assets/img/iconError.png";
import { circularPatternRecognition, getWorkerId, stopRealtime } from "../http/records";
import exportCorner from "../views/exportCorner.vue";
const router = useRouter();
const cx = ref(0);
const cy = ref(0);
const rx = ref(0);
const ry = ref(0);
const scaling_ratio = ref(1)

const jingtouW = ref(0);
const jingtouH = ref(0);

const ifShowCircle = ref(false);

const pegSrc = ref(
  import.meta.env.VITE_APP_BASE_API + `api/video/stream.mjpeg?timestamp=${Date.now()}`
);
const dataList = dataListStore();
const props = defineProps({
  getInfo: {}
});
const emit = defineEmits("resetEdit");
const imgFlag = ref(false);
const data = reactive({
  videoList: [],
  radiusChecked: false,
  total: 0,
  dialogCameraVisible: false,
  dialogRotationVisible: false,
  multipleSelection: [],
  dialogVideoVisible: false,
  circularInfo: {
    center_x: 0,
    center_y: 0,
    front_back_diameter: 0,
    side_diameter: 0
  },
  showCircularInfo:{
    center_x: 0,
    center_y: 0,
    front_back_diameter: 0,
    side_diameter: 0
  },
  bfVideoName: "",
  dialogQYSBVisible: false,
  ws: undefined,
  ifShowCircleButton:false,
  bfVideoId:''
});
const {
  videoList,
  radiusChecked,
  total,
  dialogCameraVisible,
  dialogRotationVisible,
  multipleSelection,
  dialogVideoVisible,
  circularInfo,
  bfVideoName,
  dialogQYSBVisible,
  ws,
  ifShowCircleButton,
  showCircularInfo,
  bfVideoId
} = toRefs(data);
const tableRef = ref();
const cameraRef = ref();
//获取视频列表
function getVideoList() {
  const param = {
    record_id: props.getInfo.id
  };
  listRecordings(param).then(res => {
    if (res.status == "success") {
      videoList.value = res.videos;
      total.value = res.total_count;
    }
  });
}

//多选
const handleSelectionChange = val => {
  multipleSelection.value = val;
};
const resetToZeroFn = () =>{
  resetToZero().then(res =>{
    if(res.status == "success"){
      showCircularInfo.value.center_x = Math.floor(res.data.show_info.center_x);
      showCircularInfo.value.center_y = Math.floor(res.data.show_info.center_y);
      showCircularInfo.value.front_back_diameter = Math.floor(
        res.data.show_info.front_back_diameter
      );
      showCircularInfo.value.side_diameter = Math.floor(res.data.show_info.side_diameter);
    }
  })
}
const rowClick = (row, event, column) => {
  resetToZeroFn();
  stopVideo().then(res =>{
    imgFlag.value = false;
    let path = row.filepath;
    let param = {
      source: path
    };
    startVideoFn(param,row);
  })
};

function startVideoFn(param,row){
  imgFlag.value = false;
  startVideo(param).then(res => {
    if(res.status == "success"){
      ElMessage({
        message: "播放成功",
        type: "success"
      });
      imgFlag.value = true;
      bfVideoName.value = row.filename;
      bfVideoId.value = row.record_id;
      console.log("row",row);
      
    }
    
  });
}

function changeImgFlagFn(){
  imgFlag.value = true;
}
//删除视频
function deleteVideo(filename) {
  ElMessageBox.confirm(
    `<div class="confirmTitle"><img src='${iconError}' width="20" height="20" />删除操作不可恢复，是否要确认删除</div><div class="confirmFileName">${filename}</div>`,
    "",
    {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: "确认删除",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      cancelButtonClass: "cancelBtn",
      center: true
    }
  )
    .then(() => {
      let param = {
        record_id: props.getInfo.id
      };
      deleteRecording(param, filename.split(".")[0]).then(res => {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        getVideoList();
        bfVideoName.value = "";
        bfVideoId.value = "";
      });
    })
    .catch(() => {});
}
getVideoList();
const checkInfoNameAndRedirect = () => {
  // 若已跳转过、路由实例不存在或 name 有值，直接返回
  if (props.getInfo && props.getInfo.id) return;
  // 执行跳转逻辑
  ElMessage({
    type: "warning",
    message: "实验记录不存在"
  });
  router.push("/history");
};
const stopVideoFn = () =>{
  stopVideo().then(res =>{
    imgFlag.value = false;

  })
}

function getJingTou(){
  nextTick(() => {
    let boxW = document.getElementById("centerBox2").offsetWidth;
    let boxH = (1080 * boxW) / 1920;

    jingtouW.value = boxW * 1.5;
    jingtouH.value = boxH * 1.5;
  });
  
}
onMounted(() => {
  checkInfoNameAndRedirect();
  stopVideoFn();
  getJingTou();
});

const handleCameraClose = done => {
  done();
};
const handleRotationClose = done => {
  done();
};
const updateCamera = () => {
  getJingTou();
  if( !imgFlag.value ){
    ElMessage({
      message: "目前视频流未播放",
      type: "warning"
    });
    return;
  }
  let param = {
    enable:false
  }
  setVideoCorrection(param).then(res =>{
    if(res.status == "success"){
      dialogRotationVisible.value = false;
      dialogCameraVisible.value = true;
    }
  })
  
};

function closeJz(){
  dialogCameraVisible.value = false;
  let param = {
    enable:false
  }
  setVideoCorrection(param).then(res =>{})
}
const pictureRotation = () => {
  if( !imgFlag.value ){
    ElMessage({
      message: "目前视频流未播放",
      type: "warning"
    });
    return;
  }
  dialogRotationVisible.value = true;
  dialogCameraVisible.value = false;
};
const submitCamera = () => {
  if (cameraRef.value) {
    const points = cameraRef.value.getPointsPosition();
    const result = getPointsByScreen(points);
    dataList.cameraPostion = result;
    const param = {
      corners: result,
      oversize: 1.2
    };
    correctionCorners(param).then(res => {
      console.log(res);
      ElMessage({
        message: "镜头矫正成功",
        type: "success"
      });
      dialogCameraVisible.value = false;
    });
  }
};
function getPointsByScreen(points) {
  let arr = [];
  for (let i = 0; i < points.length; i++) {
    let item = points[i];

    let newCenter = {
      x: 960,
      y: 540
    };

    let originalCenter = {
      x: jingtouW.value / 2,
      y: jingtouH.value / 2
    };

    let n = newCenter.x / originalCenter.x;

    let newX = newCenter.x + (item.x - originalCenter.x) * n;
    let newY = newCenter.y + (item.y - originalCenter.y) * n;

    arr.push([newX, newY]);
  }
  return arr;
  // return [
  //   [770, 340],
  //   [1140, 340],
  //   [1130, 700],
  //   [770, 700]
  // ];
}

const clickExportRecording = () => {
  if (!bfVideoName.value) {
    ElMessage({
      message: "请先选择视频后再导出",
      type: "error"
    });
  }
  // let name = bfVideoName.value.split(".")[0];
  // let param = {
  //   record_id: props.getInfo.id,
  // };
  let url = `${import.meta.env.VITE_APP_BASE_API}api/video/export_recording/${
    bfVideoName.value
  }?record_id=${props.getInfo.id}`;
  window.open(url, "_blank");
};
function initProgressWs(worker_id) {
  //这个接口其实没用
  ws.value = new WebSocket(
    `ws://113.44.105.79:8080/ws/circular_pattern/${worker_id}`
  );
  ws.value.onopen = function(evt) {
    console.log("Connection open.");
  };
  ws.value.onmessage = function(evt) {
    // loading.value = false;
    let res = JSON.parse(evt.data);
    if (res.type == "initialized") {
      ElMessage({
        message: "切圆识别成功",
        type: "success"
      });
      ifShowCircle.value = true;
      dialogQYSBVisible.value = false;
    }
     if(res.type == "video_file_ended"){
      ifShowCircleButton.value = false;
      dialogQYSBVisible.value = false;
      radiusChecked.value = false;
      ifShowCircle.value = false;
      ws.value.close()
    }
    if (res.type == "circular_pattern_result") {
      ifShowCircle.value = true;
      circularInfo.value.center_x = Math.floor(res.draw_info.center_x);
      circularInfo.value.center_y = Math.floor(res.draw_info.center_y);
      circularInfo.value.front_back_diameter = Math.floor(
        res.draw_info.front_back_diameter
      );
      circularInfo.value.side_diameter = Math.floor(res.draw_info.side_diameter);
      showCircularInfo.value.center_x = Math.floor(res.show_info.center_x);
      showCircularInfo.value.center_y = Math.floor(res.show_info.center_y);
      showCircularInfo.value.front_back_diameter = Math.floor(
        res.show_info.front_back_diameter
      );
      showCircularInfo.value.side_diameter = Math.floor(res.show_info.side_diameter);
      cx.value = res.draw_info.center_x;
      cy.value = res.draw_info.center_y;
      rx.value = res.draw_info.side_diameter;
      ry.value = res.draw_info.front_back_diameter;
      scaling_ratio.value = res.draw_info.scaling_ratio;
    }

  
  };
  ws.value.onclose = function(evt) {};
}
const clickCircularPatternRecognition = () => {
  if( !imgFlag.value && !bfVideoName.value ){
    ElMessage({
      message: "目前视频流未播放",
      type: "warning"
    });
    return;
  }
  dataList.circularFlag = false;
  const param = { force_align: true, revise_y: true, soft_update: true};
  dialogQYSBVisible.value = true;
  getWorkerId(param).then(res => {
    console.log(res);
     if( res.status == "error"  ){
       ElMessage({
        message: res.detail,
        type: "error"
      });
      dialogQYSBVisible.value = false;
    }
    if (res.status == "success") {
      let workerId = res.data.worker_id;
      initProgressWs(workerId);
       ifShowCircleButton.value = true;
    }
   
  });
};
const isClickCircularPatternRecognition = () =>{
  stopRealtime().then(res =>{
     ifShowCircleButton.value = false;
     radiusChecked.value = false;
     ifShowCircle.value = false;
     ws.value.close()
  })
 
}
const exportCorners = () => {
  dialogVideoVisible.value = true;
};
const handleVideoClose = () => {
  dialogVideoVisible.value = false;
};
const onChangeDialog = () => {
  dialogVideoVisible.value = false;
};
const reset = () => {
  emit("resetEdit", false);
};


</script>
<style lang="scss" scoped>
.fire-info {
  --border-radius: 6px;
  --primary-color: #4f52bb;
  --text-color: #0f1a58;
  --muted-color: #aaaaaa;
  --border-color: #c1caeb;
  --btn-width: 17.875rem;
  --btn-height: 48px;
  height: 100%;
  .in-box {
    height: 100%;
  }
  .in-box-box {
    height: 100%;
  }
  .info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 3.7vh;
    margin-bottom: 0.9vh;

    p {
      span:nth-child(1) {
        color: var(--muted-color);
      }

      span:nth-child(2) {
        color: var(--text-color);
      }
    }
  }

  .table {
    height: calc(100% - 3.7vh);
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
    overflow: auto;
  }
  .center-info {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(var(--spacing-unit) * 3);
    margin-bottom: var(--spacing-unit);

    .margin {
      margin: 0 calc(var(--spacing-unit) * 3);
      color: var(--primary-color);
    }
  }
  .center-bottom {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(var(--spacing-unit) * 3);
    margin-bottom: var(--spacing-unit);

    .margin {
      margin: 0 calc(var(--spacing-unit) * 3);
    }
  }

  .center-bottom {
    margin-top: calc(var(--spacing-unit) * 2);
  }

  .center-con {
    height: calc(100% - calc(var(--spacing-unit) * 4));
    border: 1px solid var(--border-color);
    border-radius: var(--border-radius);
    display: flex;
    justify-content: center;
    align-items: center;
    flex-flow: column;
  }

  .right_btn_container {
    display: flex;
    flex-direction: column;
    margin-top: calc(var(--spacing-unit) * 4);
    justify-content: space-between;
    .top {
      display: flex;
      justify-content: end;
      align-items: center;
      .margin {
        margin: 0 calc(var(--spacing-unit) * 3);
        color: var(--primary-color);
      }
    }
    .right_btn {
      width: var(--btn-width);
      height: var(--btn-height);
      border-top: 1px solid var(--border-color);
      border-left: 1px solid var(--border-color);
      border-right: 1px solid var(--border-color);

      :deep() {
        .el-radio-button__inner {
          width: 100%;
          height: 100%;
          border: none;
          line-height: calc(var(--spacing-unit) * 3);
        }
      }
    }

    .right_btn:last-child {
      border-bottom: 1px solid var(--border-color);
    }

    .right_btn_bottom {
      border: 1px solid var(--border-color);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: var(--btn-width);
      height: 271px;
      background: #ffffff;
      border-radius: var(--border-radius);
      padding: calc(var(--spacing-unit) * 2);
    }

    .span_title {
      margin-right: var(--spacing-unit);
      text-align: left;
      display: inline-block;
    }
  }
}

.my_btn {
  width: 64px;
  height: 32px;
  background: var(--primary-color);
  color: #fff;
  border-radius: var(--border-radius);
  margin-left: 50%;
  transform: translateX(-50%);
}

/* 1K 分辨率 (默认) */
@media (max-width: 1920px) {
  .fire-info {
    --spacing-unit: 10px;
    --btn-width: 254px;
    --btn-height: 48px;
  }
}

/* 2K 分辨率 */
@media (min-width: 1921px) and (max-width: 2560px) {
  .fire-info {
    --spacing-unit: 12px;
    --btn-width: 280px;
    --btn-height: 54px;
  }
}

/* 2.5K 分辨率 */
@media (min-width: 2561px) and (max-width: 3840px) {
  .fire-info {
    --spacing-unit: 14px;
    --btn-width: 320px;
    --btn-height: 60px;
  }
}

/* 4K 分辨率 */
@media (min-width: 3841px) {
  .fire-info {
    --spacing-unit: 16px;
    --btn-width: 380px;
    --btn-height: 72px;
  }
}
</style>
<style lang="scss">
.el-message-box {
  width: 600px;
  height: 300px;
}
.el-message-box__content {
  width: 100%;
  height: calc(100% - 100px);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-flow: column;
  text-align: center;
}
.confirmTitle {
  font-weight: 600;
  font-size: 18px;
  color: #ff5151;
  line-height: 25px;
}
.confirmFileName {
  font-size: 20px;
  color: #4f52bb;
  line-height: 28px;
  letter-spacing: 1px;
}
.cancelBtn {
  background: #eeeeee;
  border: 1px solid #eeeeee;
  border-radius: 6px 6px 6px 6px;
  font-size: 14px;
  color: #aaaaaa;
  line-height: 20px;
}
</style>
